/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.mes.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.mes.system.entity.Customer;
import org.springblade.mes.system.mapper.CustomerMapper;
import org.springblade.mes.system.service.ICustomerService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客户档案表 服务实现类
 *
 * @author shiwei
 * @since 2021-02-23
 */
@Service
@DS("system")
public class CustomerServiceImpl extends BaseServiceImpl<CustomerMapper, Customer> implements ICustomerService {
    /**
     * 根据编码查询
     *
     * @param no
     * @param tenantId
     * @param ctx
     * @return
     */
    public Customer refreshByNo(String no, String name, String tenantId, Map<String, Object> ctx, String remark) {
        String key = "Customer_" + no;
        Object v = ctx.get(key);
        if (v instanceof Customer) {
            return (Customer) v;
        }
        Customer t = null;
        if (no != null && no.length() > 0) {
            LambdaQueryWrapper<Customer> lambdaQueryWrapper = Wrappers.lambdaQuery(Customer.class);
            lambdaQueryWrapper.eq(Customer::getCustomerNumber, no).eq(Customer::getTenantId, tenantId);
            List<Customer> dataList = this.list(lambdaQueryWrapper);
            if (dataList != null && dataList.size() > 0) {
                t = dataList.get(0);
                ctx.put(key, t);
            }
        }
        if (t == null) {
            t = new Customer();
            t.setIsDeleted(0);
            t.setCustomerNumber(no);
            t.setCustomerName(name);
            t.setTenantId(tenantId);
            t.setStatus(0);
            t.setId(null);
            t.setCreateTime(new Date());
            t.setUpdateTime(new Date());
            t.setRemark(remark);
            this.save(t);
            ctx.put(key, t);
        }
        return t;
    }
}
